<?php
/**
 * User: @lose
 * Date: 2020/7/28
 * Time: 2:02 下午
 */

namespace Beerus\Modules\Store\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\store\StoreCheck as mCheck;
use Biz\model\store\StoreMsg;
use Biz\service\admin\StoreCheck as sCheck;
use Biz\service\Store\StoreBusinessService;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class CheckController extends Controller
{
    public function index(Content $content, Request $request)
    {
        Admin::script($this->setScript());
        $page = $request->input('page', 1);
        $perPage = $request->input('per_page', 20);
        $condition = self::GeTCondition($request);
        $limit = [
            ($page - 1) * $perPage, $perPage
        ];
        $result = sCheck::getListByWhere($condition, $limit);
        $grid = new pGridDataModel($result['list'], $result['count'], [
            'per_page' => $perPage
        ]);

        $gridList = Admin::grid($grid,
            function (Grid $grid) {
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->filter(function ($filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    // 在这里添加字段过滤器
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('store_id', '店铺id');
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('alias', '门店别称');
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('check_status', '审核状态')->select(mCheck::CHECK_MAP);
                    });
                    $filter->expand();//默认展开
                });
                $grid->column("store_id", '门店id');
                $grid->column("store_name", '门店名称');
                $grid->column("alias", '门店别称');
                $grid->column("admin_id", '处理人')->display(function () {
                    if (!$this->admin_id) {
                        return '-';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                })->width(60);;
                $grid->column('check_status_name', '审核状态')->display(function () {
                    $html = '';
                    $pos = $this->check_status;
                    $map = ['label-primary', 'label-warning', 'label-success', 'label-info', 'label-danger'];
                    $html .= '<span class="label ' . $map[$pos] . '">' . $this->check_status_name . '</span><br/><br/>';
                    if ($this->check_desc) {
                        $html .= '<span >失败原因:' . $this->check_desc . '</span>';
                    }
                    return $html;
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableView();
                    $actions->disableDelete();
                    $actions->disableEdit();
                    if ($actions->row->check_status == mCheck::CHECK_DEFAULT) {
                        $actions->prepend('&nbsp;<a class="fa fa-edit" target="" href=\'/admin/store/check/create/' . $actions->row->id . '\' ">审核不通过</a>');
                        $actions->prepend('<p><a class="	setSucc fa fa-align-center" data-id="' . $actions->row->id . '"  href="javascript:void(0);">审核通过</a></p>');
                    }
                });
            });
        $content->row($gridList);
        return $content
            ->header('门店信息审核')
            ->description(' ')
            ->breadcrumb(['text' => 'user']);
    }


    public function GeTCondition($request)
    {

        $condition = [];
        if ($request->input('store_id')) {
            $condition['store_id'] = $request->input('store_id');
        }

        if ($request->input('alias')) {
            $condition['alias[~]'] = $request->input('alias');
        }

        if ($request->input('check_status') != '') {
            $condition['check_status'] = $request->input('check_status');
        }

        return $condition;
    }

    public function createCheck(Content $content, Request $request, $id = 0)
    {
        $checkinfo = sCheck::getInfoById($id);
        $form = new Form($checkinfo);
        $form->hidden('account_id');
        if ($checkinfo) {
            $form->hidden('id');
        }
        $form->textarea('check_desc', '操作未通过原因')->help('请输入未通过原因....');
        $form->disableReset();
        $form->action('/admin/store/check/save');
        return $content
            ->header('操作未通过')
            ->row($form);
    }


    public function saveCheck(Request $request)
    {
        $params = $request->all();
        try {
            $id = $params['id'];
            $check_info = sCheck::getInfoById($id);
            $check_desc = $params['check_desc'];
            $data = [
                'check_desc' => $check_desc,
                'check_status' => mCheck::CHECK_FAIL,
                'admin_id' => Admin::user()->id,
            ];
            $data['edittime'] = date("y-m-d H:i:s", time());
            sCheck::updateCheck($data, $id);
            $success = new MessageBag([
                'title' => '添加成功'
            ]);
            StoreBusinessService::writeMsg($check_info['store_id'], StoreMsg::MSG_TYPE_NO_PASS, StoreMsg::MSG_SOURCE_STORE_INFO, '您添加的门店别称 ' . $check_info['alias'] . ' 未通过审核，原因为：' . $check_desc);

        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '请重试,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }

        return redirect('/admin/store/check/index')->with(compact('success'));

    }


    public function checkSucc(Request $request, $id)
    {
        try {
            $check_info = sCheck::getInfoById($id);


            $data = [
                'check_status' => mCheck::CHECK_SUCC,
                'admin_id' => Admin::user()->id,
            ];

            $data['edittime'] = date("y-m-d H:i:s", time());
            sCheck::updateCheck($data, $id);
            $status = true;
            $message = "审核成功";
            StoreBusinessService::writeMsg($check_info['store_id'], StoreMsg::MSG_TYPE_PASS, StoreMsg::MSG_SOURCE_STORE_INFO, ' 您添加的门店别称 ' . $check_info['alias'] . ' 已通过审核并已生效');
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        return response()->json(compact('status', 'message'));

    }


    /*设置scirpt
    *
    * */
    private function setScript()
    {
        return <<<SCRIPT
        //审核通过
         $('.setSucc').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要设置审核成功？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/store/check/checkSucc/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.status == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
      
SCRIPT;
    }


}